from mysql.connector.pooling import MySQLConnectionPool
from config import DB_CONFIG


pool_config = {**DB_CONFIG, "pool_name": "mypool", "pool_size": 5}
db_pool = MySQLConnectionPool(**pool_config)

def update_task_status(task_id, status, dictionary_file=None, error=None):
    conn = db_pool.get_connection()
    cursor = conn.cursor()
    try:
        query = """
        UPDATE wp_translation_tasks 
        SET status = %s, dictionary_file = %s, error = %s, updated_at = NOW()
        WHERE task_id = %s
        """
        cursor.execute(query, (status, dictionary_file, error, task_id))
        conn.commit()
    finally:
        cursor.close()
        conn.close()

def create_task(domain, page_url, task_id):
    conn = db_pool.get_connection()
    cursor = conn.cursor()
    if all([domain, page_url, task_id]):
        try:
            query = """
            INSERT INTO wp_translation_tasks (task_id, status, domain, page_url, updated_at)
            VALUES( %s, %s, %s, %s, NOW())
            """
            cursor.execute(query, (task_id, 'pending', domain, page_url))
            conn.commit()
        finally:
            cursor.close()
            conn.close()

def create_task_table():
    conn = db_pool.get_connection()
    cursor = conn.cursor()
    try:
        cursor.execute("""
        CREATE TABLE IF NOT EXISTS wp_translation_tasks (
            task_id VARCHAR(255) PRIMARY KEY,
            domain VARCHAR(255) NOT NULL,
            page_url TEXT NOT NULL,
            status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
            dictionary_file TEXT,
            error TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
        """)
        conn.commit()
    finally:
        cursor.close()
        conn.close()
